package com.rising.bloom;

import com.carrotsearch.sizeof.RamUsageEstimator;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2020/9/12 12:25
 */
public class BloomFilterTest {
    public static void main(String[] args) {
        System.out.println("===================测试布隆过滤器===================");
        int datas = 1000 * 10000;
        BloomFilter bloomFilter = new BloomFilter(datas, 0.001);
        for (int i = 0; i < datas; i++) {
            bloomFilter.add(new String(String.valueOf(i)));
        }
        //测试1000万个不存在，看误报率
        int falseSum = 0;
        long startTime = System.currentTimeMillis();
        for (int i = datas; i < datas + 1000 * 10000; i++) {
            boolean contain = bloomFilter.contain(String.valueOf(i));
            if (contain) {
                falseSum++;
            }
        }
        long endTime = System.currentTimeMillis();
        //double bloomByteSize = new BigDecimal(RamUsageEstimator.sizeOfObject(bloomFilter) / (1024.0 * 1024)).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println("布隆过滤器总数：" + bloomFilter.getSum());
        System.out.println("布隆过滤器误报数：" + falseSum);
        System.out.println("布隆过滤器占用空间：" + RamUsageEstimator.humanSizeOf(bloomFilter) + "字节，字节：" + RamUsageEstimator.sizeOfAll(bloomFilter));
        System.out.println("布隆过滤器处理时间：" + (endTime - startTime) + "ms");
        System.out.println("===================测试HashMap===================");
        Map<String, Object> map = new HashMap<String, Object>(datas);
        for (int i = 0; i < datas; i++) {
            map.put(i + "", null);
        }
        //测试1000万个不存在，看误报率
        falseSum = 0;
        startTime = System.currentTimeMillis();
        for (int i = datas; i < datas + 1000 * 10000; i++) {
            boolean contain = map.containsKey(i + "");
            if (contain) {
                falseSum++;
            }
        }
        endTime = System.currentTimeMillis();
        //double mapByteSize = new BigDecimal(RamUsageEstimator.sizeOfMap(map) / (1024.0 * 1024)).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println("HashMap总数：" + map.size());
        System.out.println("HashMap误报数：" + falseSum);
        System.out.println("HashMap占用空间：" + RamUsageEstimator.humanSizeOf(map) + "字节，字节：" + RamUsageEstimator.sizeOfAll(map));
        System.out.println("HashMap处理时间：" + (endTime - startTime) + "ms");
    }
}
